# coding: utf-8

from wtforms import DecimalField, StringField, DateField
from wtforms.validators import DataRequired, Length, NumberRange, ValidationError, AnyOf, Optional

from server.apps.account.models import AccBasic
from server.apps.fund.models import FundBasic
from server.utils.forms import BaseForm


class FundTradeForm(BaseForm):
    acc_id = StringField(validators=[DataRequired(), Length(min=6, max=6, message="账号错误")])
    fund = StringField(validators=[DataRequired(), Length(min=6, max=6, message="转出账号格式错误")])
    name = StringField(validators=[DataRequired()])
    post_date = DateField(validators=[DataRequired()])
    operation = StringField(validators=[DataRequired(), AnyOf(["申购", "赎回", "现金红利", "分红再投资"])])
    amount = DecimalField(validators=[Optional(), NumberRange(min=0, message="金额不能为负")])
    number = DecimalField(validators=[Optional(), NumberRange(min=0, message="数量不能为负")])

    def validate_acc_id(self, value):
        if not AccBasic.query.filter(AccBasic.acc_id == value.data).first():
            raise ValidationError("账号不存在")

    def validate_fund(self, value):
        if not FundBasic.query.filter(FundBasic.fund == value.data).first():
            raise ValidationError("基金不在关注范围内")
